<template>
  <div>
    <div>
      运营账号管理
    </div>
    <!--搜索框-->
    <div class="search-box">
      <!--<el-form ref="filter" :model="filter">-->
        <!--<el-form-item label="用号名称">-->
          <!--<el-input v-model="filter.name" size="small" style="width:200px;margin-right:10px;"></el-input>-->
          <!--<el-button size="small" type="warning">查询</el-button>-->
          <!--<el-button size="small" type="primary" @click="addUser">新增</el-button>-->
        <!--</el-form-item>-->
      <!--</el-form>-->
      <el-button size="small" type="primary" @click="addUser">新增</el-button>
    </div>
    <!--用户列表-->
    <div style="overflow:hidden;border-top:1px solid #ccc">
      <el-table :data="userList" stripe style="width:100%" v-loading="loading">
        <el-table-column prop="username" label="用户姓名" min-width="200"></el-table-column>
        <el-table-column prop="name" label="角色" min-width="200"></el-table-column>
        <el-table-column prop="institutionName" label="银行" min-width="200"></el-table-column>
        <el-table-column label="操作" min-width="200">
          <template slot-scope="scope">
            <el-button size="mini" @click="editUser(scope.$index, scope.row)">修改</el-button>
            <el-button size="mini" type="danger" @click="deleteUser(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页功能-->
      <el-pagination
        style="margin-top:20px;justify-content:flex-end;display:flex;"
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page.sync="currentPage"
        :page-size="10"
        layout="prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <!--新增弹窗-->
    <el-dialog title="新增账号" :visible.sync="addDialogVisible" width="30%" :close-on-click-modal="false">
      <el-form :model="addForm" ref="addForm" :rules="addRules" label-width="80px" >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="addForm.sex">
            <el-radio label="1">男</el-radio>
            <el-radio label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门" prop="branchId">
          <el-select v-model="addForm.branchId" placeholder="请选择部门">
            <el-option v-for="item in branchIdArr"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="post">
          <el-select v-model="addForm.post" placeholder="请选择角色">
            <el-option v-for="item in roleArr"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="Email">
          <el-input v-model="addForm.Email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model.number="addForm.phone" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="有效期" prop="validdate">
          <el-date-picker
            v-model="addForm.validdate"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="addCancel">取 消</el-button>
        <el-button size="small" type="primary" @click="addSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!--修改弹窗-->
    <el-dialog title="编辑账号" :visible.sync="editDialogVisible" width="30%" :close-on-click-modal="false">
      <el-form :model="editForm" ref="editForm" :rules="editRules" label-width="80px" >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="editForm.sex">
            <el-radio label="1">男</el-radio>
            <el-radio label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门" prop="branchId">
          <el-select v-model="editForm.branchId" placeholder="请选择部门">
            <el-option v-for="item in branchIdArr"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="post">
          <el-select v-model="editForm.post" placeholder="请选择角色">
            <el-option v-for="item in roleArr"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="Email">
          <el-input v-model="editForm.Email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model.number="editForm.phone" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="有效期" prop="validdate">
          <el-date-picker
            v-model="editForm.validdate"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="editCancel">取 消</el-button>
        <el-button size="small" type="primary" @click="editSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import server from '../../services/index'
  var validatePhone = (rule, value, callback) => {
    if(value === ''){
      callback(new Error('请输入电话号码！'));
    }else{
      if(!(/^1(3|4|5|7|8)\d{9}$/.test(value))){
        callback(new Error('请输入正确电话号码！'));
      }
      callback();
    }
  };
  export default {
    name: "operationAccount",
    components: {},
    data () {
      return {
        filter:{
          name: "",
        },
        userList: [],
        loading: false,
        total: 0,
        currentPage: 1,
        pageSize: 10,
        addDialogVisible: false,
        branchIdArr:[],
        roleArr:[],
        addForm: {
          username: "",
          password: "",
          sex: "1",
          branchId: "",
          post: "",
          Email: "",
          phone: "",
          validdate: "",
        },
        addRules: {
          username: [
            { required: true, message: '请输入用户名！', trigger: ['blur', 'change'] },
          ],
          password: [
            { required: true, message: '请输入密码！', trigger: ['blur', 'change'] },
          ],
          sex: [
            { required: true, message: '请选择性别！', trigger: ['blur', 'change'] },
          ],
          branchId: [
            { required: true, message: '请选择部门！', trigger: ['blur', 'change'] },
          ],
          post: [
            { required: true, message: '请选择角色！', trigger: ['blur', 'change'] },
          ],
          Email: [
            { type: 'email', message: '请输入正确的邮箱地址！', trigger: 'blur' }
          ],
          phone: [
            { validator: validatePhone, trigger: 'blur' },
          ],
          validdate: [
            { required: true, message: '请输入有效期！', trigger: ['blur', 'change'] },
          ],
        },
        editDialogVisible: false,
        editForm: {
          username: "",
          password: "",
          sex: "1",
          branchId: "",
          post: "",
          Email: "",
          phone: "",
          validdate: "",
          validdateOld:"",
        },
        editRules: {
          username: [
            { required: true, message: '请输入用户名！', trigger: ['blur', 'change'] },
          ],
          password: [
            { required: true, message: '请输入密码！', trigger: ['blur', 'change'] },
          ],
          sex: [
            { required: true, message: '请选择性别！', trigger: ['blur', 'change'] },
          ],
          branchId: [
            { required: true, message: '请选择部门！', trigger: ['blur', 'change'] },
          ],
          post: [
            { required: true, message: '请选择角色！', trigger: ['blur', 'change'] },
          ],
          Email: [
            { type: 'email', message: '请输入正确的邮箱地址！', trigger: 'blur' }
          ],
          phone: [
            { validator: validatePhone, trigger: 'blur' },
          ],
          validdate: [
            { required: true, message: '请输入有效期！', trigger: ['blur', 'change'] },
          ],
        },
      }
    },
    methods:{
      getDropDownList(){
        this.branchIdArr = [];
        this.roleArr = [];
        //请求部门列表
        $.ajax({
          url:server.selectBranch.url,
          type:'get',
          dataType:'json',
          success:res => {
            if(res.code == 1){
              res.result.forEach(item=>{
                this.branchIdArr.push({
                  value:item.institutionId,
                  label:item.institutionName
                })
              })
            }
          },
          error:err =>{
            this.$message({
              message: err.responseJSON.error,
              type: 'error'
            });
          }
        });
        //请求角色列表
        $.ajax({
          url:server.roleList.url,
          type:'get',
          dataType:'json',
          success:res => {
            if(res.code == 1){
              res.result.roleList.forEach(item=>{
                this.roleArr.push({
                  value:item.roleId,
                  label:item.name
                })
              })
            }
          },
          error:err =>{
            this.$message({
              message: err.responseJSON.error,
              type: 'error'
            });
          }
        });
      },
      getListData(){
        this.loading = true;
        let params = {
          pages: this.pageSize,
          pageNum: this.currentPage,
        }
        $.ajax({
          url:server.userList.url,
          type:'get',
          data:params,
          dataType:'json',
          success:res => {
            if(res.code == 1){
              this.loading = false;
              this.userList = res.result.userList;
              this.total = res.result.total;
            }
          },
          error:err =>{
            this.$message({
              message: err.responseJSON.error,
              type: 'error'
            });
          }
        });
      },
      sizeChange(val){
        this.pageSize = val;
        this.getListData();
      },
      currentChange(val){
        this.currentPage = val;
        this.getListData();
      },
      addUser(){
        this.addDialogVisible = true;
      },
      addSubmit(){
        this.$refs.addForm.validate((valid) => {
          if(valid){
            this.$confirm('确认添加新账号？').then(() => {
              let params = {
                username: this.addForm.username,
                password: this.addForm.password,
                sex: this.addForm.sex,
                branchId: this.addForm.branchId,
                post: this.addForm.post,
                Email: this.addForm.Email,
                phone: this.addForm.phone,
                validdate: this.getNowFormatDate(this.addForm.validdate),
              }
              $.ajax({
                url:server.addUser.url,
                type:'post',
                data:params,
                dataType:'json',
                success:res => {
                  if(res.code == 1){
                    this.$message({
                      message: '新增成功！',
                      type: 'success'
                    });
                    this.addDialogVisible = false;
                    this.$refs.addForm.resetFields();
                    this.getListData();
                  }
                },
                error:err =>{
                  this.$message({
                    message: err.responseJSON.error,
                    type: 'error'
                  });
                }
              });
            }).catch(() => {});
          }else{
            return false;
          }
        });
      },
      addCancel(){
        this.addDialogVisible = false;
        this.$refs.addForm.resetFields();
      },
      deleteUser(index, row){
        this.$confirm('确认删除该账号？').then(() => {
          $.ajax({
            url:server.deleteUser.url,
            type:'get',
            data:{
              userId:row.userId
            },
            dataType:'json',
            success:res => {
              if(res.code == 1){
                this.$message({
                  message: '删除成功！',
                  type: 'success'
                });
                this.getListData();
              }
            },
            error:err =>{
              this.$message({
                message: err.responseJSON.error,
                type: 'error'
              });
            }
          });
        }).catch(() => {});
      },
      editUser(index, row){
        $.ajax({
          url:server.selectById.url,
          type:'get',
          data:{'userId':row.userId},
          dataType:'json',
          success:res => {
            if(res.code == 1){
              this.editForm.userId = res.result.userId;
              this.editForm.username = res.result.username;
              this.editForm.password = res.result.password;
              this.editForm.sex = res.result.sex;
              this.editForm.branchId = res.result.branchId;
              this.editForm.post = res.result.post;
              this.editForm.Email = res.result.email;
              this.editForm.phone = res.result.phone;
              this.editForm.validdate = res.result.validdate;
              this.editForm.validdateOld = res.result.validdate;
              this.editDialogVisible = true;
            }
          },
          error:err =>{
          this.$message({
            message: err.responseJSON.error,
            type: 'error'
          });
        }
        });
      },
      editSubmit(){
        this.$refs.editForm.validate((valid) => {
          if(valid){
            this.$confirm('确认修改该账号？').then(() => {
              let params = {};
              params.userId = this.editForm.userId;
              params.username = this.editForm.username;
              params.password = this.editForm.password;
              params.sex = this.editForm.sex;
              params.branchId = this.editForm.branchId;
              params.post = this.editForm.post;
              params.Email = this.editForm.Email;
              params.phone = this.editForm.phone;
              params.validdate = this.editForm.validdate==this.editForm.validdateOld?this.editForm.validdate:this.getNowFormatDate(this.editForm.validdate);
              console.log(params)
              $.ajax({
                url:server.updateUser.url,
                type:'post',
                data:params,
                dataType:'json',
                success:res => {
                  if(res.code == 1){
                    this.$message({
                      message: '新增成功！',
                      type: 'success'
                    });
                    this.editDialogVisible = false;
                    this.$refs.editForm.resetFields();
                    this.getListData();
                  }
                },
                error:err =>{
                  this.$message({
                    message: err.responseJSON.error,
                    type: 'error'
                  });
                }
              });
            }).catch(() => {});
          }else{
            return false;
          }
        });
      },
      editCancel(){
        this.editDialogVisible = false;
        this.$refs.editForm.resetFields();
      },
      getNowFormatDate(time) {
        var date = time;
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
          month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
          strDate = "0" + strDate;
        }
        var currentdate = year + "-" + month + "-" + strDate;
        return currentdate;
      },
    },
    mounted(){
      if(!window.sessionStorage.getItem("token"))this.$router.push({path: '/'});
      this.getDropDownList();
      this.getListData()
    }
  }
</script>

<style scoped>
  .search-box{
    margin: 20px 0;
  }
</style>
